<template>
	<div class="merchant-shop-detail">
		<!-- 顶部导航 -->
		<header class="page-header">
			<button class="back-btn" @click="handleBack">← 返回</button>
			<p>店铺详情</p>
		</header>

		<!-- 店铺基础信息 -->
		<div class="shop-basic-info">
			<div class="shop-cover">
				<img :src="currentShop.businessImg || 'https://picsum.photos/id/26/200/120'" alt="店铺封面" />
			</div>
			<div class="shop-info">
				<h3 class="shop-name">{{ currentShop.businessName }}</h3>
				<div class="shop-status status-open">
					营业中
				</div>
				<p class="shop-address"><i class="icon">📍</i> {{ currentShop.businessAddress }}</p>
				<div class="shop-price-info">
					<span class="price-item">起送: ¥{{ currentShop.startPrice || 0 }}</span>
					<span class="price-item">配送: ¥{{ currentShop.deliveryPrice || 0 }}</span>
				</div>
			</div>
		</div>

		<!-- 商品列表标题 -->
		<div class="section-title">
			<span>商品管理</span>
		</div>

		<!-- 加载状态 -->
		<div v-if="loading" class="loading">
			<i class="fa fa-spinner fa-spin"></i> 加载中...
		</div>

		<!-- 商品列表区域 -->
		<div class="goods-list-container" v-else>
			<!-- 列表为空提示 -->
			<div class="empty-tip" v-if="goodsList.length === 0">
				<img src="https://img.icons8.com/fluency/96/000000/empty-box.png" alt="暂无商品" class="empty-icon" />
				<p>暂无商品，点击"新增商品"添加</p>
			</div>

			<!-- 商品列表 -->
			<ul class="goods-list" v-else>
				<li class="goods-item" v-for="(goods, index) in goodsList" :key="goods.id">
					<div class="goods-info">
						<div class="goods-cover">
							<img :src="goods.foodImg || 'https://picsum.photos/id/43/100/100'" alt="商品封面" />
						</div>
						<div class="goods-main">
							<h4 class="goods-name">{{ goods.foodName }}</h4>
							<p class="goods-desc">{{ goods.foodExplain || '暂无描述' }}</p>
							<div class="goods-price-stock">
								<span class="goods-price">价格：¥{{ goods.foodPrice }}</span>
								<span class="goods-stock" v-if="goods.stock !== undefined">库存：{{ goods.stock }}</span>
							</div>
							<div class="goods-status-tag" :class="getGoodsStatusClass(goods)">
								{{ getGoodsStatusText(goods) }}
							</div>
						</div>
					</div>

					<!-- 商品操作区 -->
					<div class="goods-actions">
						<button class="btn edit-btn" @click="handleEditGoods(goods)">修改</button>
						<button class="btn delete-btn" @click="handleDeleteGoods(goods)">删除</button>
					</div>
				</li>
			</ul>
		</div>

		<!-- 新增商品按钮 -->
		<div class="add-goods-btn-container">
			<button class="add-goods-btn" @click="handleAddGoods">新增商品</button>
		</div>

		<!-- 新增/编辑商品弹窗 -->
		<div class="modal-mask" v-if="showGoodsModal">
			<div class="modal-content">
				<div class="modal-header">
					<h4>{{ isAddGoods ? '新增商品' : '编辑商品' }}</h4>
					<i class="fa fa-times close-icon" @click="showGoodsModal = false"></i>
				</div>
				<div class="modal-body">
					<div class="input-group">
						<label>商品名称 *</label>
						<input type="text" v-model="form.foodName" placeholder="请输入商品名称" />
					</div>
					<div class="input-group">
						<label>商品描述</label>
						<textarea v-model="form.foodExplain" placeholder="请输入商品描述" rows="3"></textarea>
					</div>
					<div class="input-group">
						<label>商品价格 *</label>
						<input type="number" v-model.number="form.foodPrice" placeholder="请输入商品价格" min="0"
							step="0.01" />
					</div>
					<div class="input-group">
						<label>商品图片URL</label>
						<input type="text" v-model="form.foodImg" placeholder="请输入商品图片地址" />
					</div>
					<div class="input-group">
						<label>备注</label>
						<textarea v-model="form.remarks" placeholder="请输入备注信息" rows="2"></textarea>
					</div>
				</div>
				<div class="modal-footer">
					<button class="cancel-btn" @click="showGoodsModal = false">取消</button>
					<button class="confirm-btn" @click="confirmGoods" :disabled="saving">
						{{ saving ? '保存中...' : '确认' }}
					</button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		name: 'ShopDetail',
		data() {
			return {
				// 从localStorage获取店铺数据（替换sessionStorage）
				currentShop: {},
				// 商品列表数据
				goodsList: [],
				// 加载状态
				loading: true,
				// 保存状态
				saving: false,
				showGoodsModal: false,
				isAddGoods: true,
				form: {
					foodName: '',
					foodExplain: '',
					foodImg: '',
					foodPrice: 0,
					remarks: '',
					business: {
						id: 0
					}
				},
				editingGoods: null
			};
		},
		created() {
			this.loadShopData();
		},
		watch: {
			// 当店铺数据加载完成后，加载商品列表
			currentShop: {
				handler(newVal) {
					if (newVal.id) {
						this.loadGoodsData();
					}
				},
				immediate: true
			}
		},
		methods: {
			// 加载店铺数据 - 改为从localStorage读取
			loadShopData() {
				const shopData = localStorage.getItem('currentShopDetail');
				if (shopData) {
					this.currentShop = JSON.parse(shopData);
					// 设置商品表单中的商家ID
					this.form.business.id = this.currentShop.id;
				} else {
					this.currentShop = {
						id: 0,
						businessName: '未知店铺',
						businessAddress: '地址未知',
						businessImg: 'https://picsum.photos/id/26/200/120',
						startPrice: 0,
						deliveryPrice: 0
					};
					alert('未找到店铺信息，请从店铺管理页面进入');
				}
			},

			// 加载商品数据 - 使用正确的API参数格式
			async loadGoodsData() {
				this.loading = true;
				try {
					const token = localStorage.getItem('jwt_token');
					if (!token) {
						throw new Error('未找到认证信息');
					}

					const headers = {
						'Authorization': `Bearer ${token}`,
						'Content-Type': 'application/json'
					};

					// 根据API要求，使用query参数传递商家ID
					const response = await this.$axios.get('/api/foods', {
						headers,
						params: {
							business: this.currentShop.id,
							order: 'price_asc' // 默认按价格升序排序
						}
					});

					this.goodsList = response.data.data || [];

				} catch (error) {
					console.error('加载商品失败:', error);
					alert('加载商品失败: ' + (error.response?.data?.message || error.message));
				} finally {
					this.loading = false;
				}
			},

			// 返回店铺管理页面
			handleBack() {
				this.$router.push('/businessShopManage');
			},

			// 获取商品状态样式
			getGoodsStatusClass(goods) {
				return goods.deleted ? 'status-off' : 'status-on';
			},

			// 获取商品状态文本
			getGoodsStatusText(goods) {
				return goods.deleted ? '已下架' : '上架中';
			},

			// 处理删除商品 - 使用DELETE接口（物理删除）
			async handleDeleteGoods(goods) {
				if (!confirm(`确定要永久删除商品【${goods.foodName}】吗？此操作不可恢复！`)) {
					return;
				}

				try {
					const token = localStorage.getItem('jwt_token');
					const headers = {
						'Authorization': `Bearer ${token}`,
						'Content-Type': 'application/json'
					};

					// 使用DELETE接口进行物理删除
					const response = await this.$axios.delete(`/api/foods/${goods.id}`, {
						headers
					});

					console.log('删除响应:', response.data);

					if (response.data.success) {
						alert('商品删除成功');
						// 重新加载商品列表
						this.loadGoodsData();
					} else {
						alert('商品删除失败: ' + (response.data.message || '未知错误'));
					}

				} catch (error) {
					console.error('商品删除失败:', error);
					alert('商品删除失败: ' + (error.response?.data?.message || error.message));
				}
			},

			// 处理下架/上架商品 - 使用PUT接口（软删除）
			async handleToggleGoodsStatus(goods) {
				const action = goods.deleted ? '上架' : '下架';
				if (!confirm(`确定要${action}商品【${goods.foodName}】吗？`)) {
					return;
				}

				try {
					const token = localStorage.getItem('jwt_token');
					const headers = {
						'Authorization': `Bearer ${token}`,
						'Content-Type': 'application/json'
					};

					// 构建完整的商品数据，只修改deleted字段
					const updateData = {
						// 系统字段
						id: goods.id,
						createTime: goods.createTime,
						updateTime: goods.updateTime,
						creator: goods.creator,
						updater: goods.updater,

						// 业务字段 - 保持原值
						foodName: goods.foodName,
						foodExplain: goods.foodExplain || '',
						foodImg: goods.foodImg || '',
						foodPrice: goods.foodPrice,
						remarks: goods.remarks || '',

						// 商家信息
						business: goods.business || {
							id: this.currentShop.id
						},

						// 修改删除状态
						deleted: !goods.deleted
					};

					// 调用更新接口，修改deleted状态实现软删除/上架
					const response = await this.$axios.put(`/api/foods/${goods.id}`, updateData, {
						headers
					});

					console.log(`${action}商品响应:`, response.data);

					alert(`商品${action}成功`);
					// 重新加载商品列表
					this.loadGoodsData();

				} catch (error) {
					console.error(`商品${action}失败:`, error);
					alert(`商品${action}失败: ` + (error.response?.data?.message || error.message));
				}
			},

			// 处理新增商品点击
			handleAddGoods() {
				this.isAddGoods = true;
				this.form = {
					foodName: '',
					foodExplain: '',
					foodImg: '',
					foodPrice: 0,
					remarks: '',
					business: {
						id: this.currentShop.id // 设置当前店铺ID
					}
				};
				this.editingGoods = null;
				this.showGoodsModal = true;
			},

			// 处理编辑商品
			handleEditGoods(goods) {
				this.isAddGoods = false;
				this.editingGoods = goods;
				// 复制商品数据，仅保留需要编辑的字段
				this.form = {
					foodName: goods.foodName,
					foodExplain: goods.foodExplain || '',
					foodImg: goods.foodImg || '',
					foodPrice: goods.foodPrice,
					remarks: goods.remarks || ''
				};
				this.showGoodsModal = true;
			},

			// 确认新增/编辑商品
			async confirmGoods() {
				// 表单验证
				if (!this.form.foodName.trim()) {
					alert('商品名称不能为空');
					return;
				}

				if (this.form.foodPrice === '' || this.form.foodPrice < 0) {
					alert('请输入有效的商品价格');
					return;
				}

				this.saving = true;

				try {
					const token = localStorage.getItem('jwt_token');
					const headers = {
						'Authorization': `Bearer ${token}`,
						'Content-Type': 'application/json'
					};

					if (this.isAddGoods) {
						// 新增商品 - 只需要传递必要字段
						const createData = {
							foodName: this.form.foodName.trim(),
							foodExplain: this.form.foodExplain,
							foodImg: this.form.foodImg,
							foodPrice: parseFloat(this.form.foodPrice),
							remarks: this.form.remarks,
							business: {
								id: this.currentShop.id
							}
						};

						await this.$axios.post('/api/foods', createData, {
							headers
						});
						alert('商品新增成功');

					} else {
						// 构建完整的编辑数据
						const requestData = {
							// 从原商品数据获取系统字段
							id: this.editingGoods.id,
							createTime: this.editingGoods.createTime,
							updateTime: this.editingGoods.updateTime,
							creator: this.editingGoods.creator,
							updater: this.editingGoods.updater,
							deleted: this.editingGoods.deleted,

							// 更新的表单字段
							foodName: this.form.foodName.trim(),
							foodExplain: this.form.foodExplain,
							foodImg: this.form.foodImg,
							foodPrice: parseFloat(this.form.foodPrice),
							remarks: this.form.remarks,

							// 完整的商家信息
							business: this.editingGoods.business
						};

						const response = await this.$axios.put(`/api/foods/${this.editingGoods.id}`, requestData, {
							headers
						});
						console.log('编辑响应:', response.data);

						alert('商品编辑成功');
					}

					this.showGoodsModal = false;
					// 重新加载商品列表
					await this.loadGoodsData();

				} catch (error) {
					console.error('保存商品失败:', error);
					console.error('错误详情:', error.response?.data);
					alert('保存商品失败: ' + (error.response?.data?.message || error.message));
				} finally {
					this.saving = false;
				}
			}
		}
	};
</script>

<style scoped>
	.back-btn {
		position: absolute;
		left: 4vw;
		background: rgba(255, 255, 255, 0.2);
		border: none;
		color: white;
		padding: 1.5vw 3vw;
		border-radius: 4px;
		font-size: 3.2vw;
		cursor: pointer;
	}

	/* 添加店铺价格信息样式 */
	.shop-price-info {
		display: flex;
		gap: 2vw;
		margin-top: 1vw;
	}

	.price-item {
		background-color: #f0f8ff;
		padding: 0.5vw 2vw;
		border-radius: 2vw;
		font-size: 2.8vw;
		color: #0097FF;
	}

	/* 加载状态 */
	.loading {
		text-align: center;
		padding: 10vw;
		font-size: 4vw;
		color: #0097FF;
	}

	/* 文本域样式 */
	.input-group textarea {
		width: 100%;
		padding: 2vw;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 3.2vw;
		font-family: inherit;
		resize: vertical;
		min-height: 20vw;
	}

	.input-group textarea:focus {
		outline: none;
		border-color: #0097FF;
	}

	/* 禁用按钮样式 */
	.confirm-btn:disabled {
		background-color: #ccc;
		cursor: not-allowed;
	}

	/* 其他样式保持不变 */

	/* 全局样式重置 */
	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
		list-style: none;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
	}

	/* 页面容器 */
	.merchant-shop-detail {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-top: 0;
		/* 修复顶部留白问题，移除额外的顶部内边距 */
		padding-bottom: 15vw;
	}

	/* 顶部导航 */
	.page-header {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		color: #fff;
		font-size: 4.8vw;
		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
	}

	.back-btn {
		position: absolute;
		left: 4vw;
		background: rgba(255, 255, 255, 0.2);
		border: none;
		color: white;
		padding: 1.5vw 3vw;
		border-radius: 4px;
		font-size: 3.2vw;
		cursor: pointer;
		transition: background 0.3s ease;
	}

	.back-btn:hover {
		background: rgba(255, 255, 255, 0.3);
	}

	/* 店铺基础信息 - 新增顶部内边距，避免被导航栏遮挡 */
	.shop-basic-info {
		margin-top: 12vw;
		/* 与导航栏高度一致，避免内容被遮挡 */
		width: 100%;
		background-color: #fff;
		padding: 4vw 3vw;
		display: flex;
		align-items: center;
		gap: 3vw;
		margin-bottom: 3vw;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		border-radius: 8px;
	}

	/* 添加店铺价格信息样式 */
	.shop-price-info {
		display: flex;
		gap: 2vw;
		margin-top: 1vw;
	}

	.price-item {
		background-color: #f0f8ff;
		padding: 0.5vw 2vw;
		border-radius: 2vw;
		font-size: 2.8vw;
		color: #0097FF;
	}

	/* 区域标题 */
	.section-title {
		padding: 0 3vw;
		margin-bottom: 2vw;
	}

	.section-title span {
		display: inline-block;
		font-size: 3.5vw;
		color: #333;
		font-weight: 600;
		padding-left: 1.5vw;
		border-left: 3px solid #0097FF;
	}

	/* 店铺封面 */
	.shop-cover {
		width: 25vw;
		height: 15vw;
		border-radius: 4px;
		overflow: hidden;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
	}

	.shop-cover img {
		width: 100%;
		height: 100%;
		object-fit: cover;
		transition: transform 0.3s ease;
	}

	.shop-cover img:hover {
		transform: scale(1.05);
	}

	.shop-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 2vw;
	}

	.shop-name {
		font-size: 3.5vw;
		color: #333;
		font-weight: 600;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	/* 店铺状态 */
	.shop-status {
		padding: 0.5vw 2vw;
		border-radius: 2vw;
		font-size: 2.5vw;
		font-weight: 500;
		display: inline-block;
	}

	.status-open {
		background-color: #e6f7ef;
		color: #38CA73;
	}

	.status-close {
		background-color: #fff2e8;
		color: #ff7d00;
	}

	.shop-address,
	.shop-contact {
		font-size: 3vw;
		color: #666;
		display: flex;
		align-items: center;
		gap: 1.5vw;
	}

	.icon {
		font-size: 3.2vw;
	}

	/* 商品列表容器 */
	.goods-list-container {
		width: 100%;
		padding: 0 3vw 3vw;
	}

	/* 加载状态 */
	.loading {
		text-align: center;
		padding: 15vw 0;
		font-size: 4vw;
		color: #0097FF;
	}

	/* 空列表提示 */
	.empty-tip {
		width: 100%;
		padding: 15vw 0;
		text-align: center;
		color: #999;
	}

	.empty-icon {
		width: 20vw;
		height: 20vw;
		margin-bottom: 3vw;
		opacity: 0.6;
	}

	.empty-tip p {
		font-size: 3.2vw;
	}

	/* 商品列表 */
	.goods-list {
		display: flex;
		flex-direction: column;
		gap: 3vw;
	}

	/* 商品列表项 */
	.goods-item {
		width: 100%;
		background-color: #fff;
		border-radius: 8px;
		padding: 3vw;
		display: flex;
		flex-direction: column;
		gap: 2vw;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		transition: box-shadow 0.3s ease;
	}

	.goods-item:hover {
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
	}

	/* 商品基础信息（封面+名称+描述+价格库存） */
	.goods-info {
		display: flex;
		align-items: center;
		gap: 3vw;
	}

	/* 商品封面图 */
	.goods-cover {
		width: 20vw;
		height: 15vw;
		border-radius: 4px;
		overflow: hidden;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
	}

	.goods-cover img {
		width: 100%;
		height: 100%;
		object-fit: cover;
		transition: transform 0.3s ease;
	}

	.goods-cover img:hover {
		transform: scale(1.05);
	}

	/* 商品名称+描述+价格库存 */
	.goods-main {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 1vw;
	}

	.goods-name {
		font-size: 3.5vw;
		color: #333;
		font-weight: 600;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.goods-desc {
		font-size: 3vw;
		color: #666;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.goods-price-stock {
		display: flex;
		gap: 2vw;
		font-size: 3vw;
		color: #666;
	}

	/* 商品状态标签 */
	.goods-status-tag {
		display: inline-block;
		padding: 0.5vw 2vw;
		border-radius: 2vw;
		font-size: 2.5vw;
		font-weight: 500;
		margin-top: 1vw;
	}

	.status-on {
		background-color: #e6f4ff;
		color: #0097FF;
	}

	.status-off {
		background-color: #f5f5f5;
		color: #999;
	}

	/* 商品操作区 */
	.goods-actions {
		display: flex;
		justify-content: flex-end;
		gap: 2vw;
		margin-top: 2vw;
		padding-left: 23vw;
		/* 与商品封面宽度对齐 */
	}

	.status-select {
		padding: 1.5vw;
		border-radius: 4px;
		font-size: 3vw;
		border: 1px solid #ddd;
		outline: none;
		background-color: #fff;
		transition: border-color 0.3s ease;
	}

	.status-select:focus {
		border-color: #0097FF;
	}

	/* 按钮样式 */
	.btn {
		padding: 1.5vw 4vw;
		border-radius: 4px;
		font-size: 3vw;
		font-weight: 500;
		border: none;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.edit-btn {
		background-color: #e6f4ff;
		color: #0097FF;
	}

	.edit-btn:hover {
		background-color: #d1eaff;
	}

	.delete-btn {
		background-color: #fff1f0;
		color: #f5222d;
	}

	.delete-btn:hover {
		background-color: #ffe8e6;
	}

	/* 新增商品按钮容器 */
	.add-goods-btn-container {
		width: 100%;
		box-sizing: border-box;
		padding: 4vw 3vw 0 3vw;
	}

	/* 新增商品按钮 */
	.add-goods-btn {
		width: 100%;
		height: 10vw;
		font-size: 3.8vw;
		font-weight: 700;
		color: #fff;
		background-color: #38CA73;
		border-radius: 4px;
		border: none;
		outline: none;
		cursor: pointer;
		transition: background-color 0.3s ease;
		box-shadow: 0 2px 5px rgba(56, 202, 115, 0.3);
	}

	.add-goods-btn:hover {
		background-color: #2db366;
	}

	/* 弹窗遮罩 */
	.modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 2000;
	}

	/* 弹窗内容 */
	.modal-content {
		width: 85%;
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
	}

	/* 弹窗头部 */
	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 3vw 3vw;
		border-bottom: 1px solid #f5f5f5;
	}

	.modal-header h4 {
		font-size: 3.5vw;
		color: #333;
		font-weight: 600;
	}

	/* 关闭图标 */
	.close-icon {
		font-size: 4vw;
		color: #999;
		cursor: pointer;
		transition: color 0.3s ease;
	}

	.close-icon:hover {
		color: #333;
	}

	/* 弹窗体 */
	.modal-body {
		padding: 3vw;
	}

	/* 输入组 */
	.input-group {
		margin-bottom: 3vw;
	}

	.input-group label {
		display: block;
		font-size: 3vw;
		color: #333;
		margin-bottom: 1vw;
	}

	.required {
		color: #ff4d4f;
	}

	.input-group input,
	.input-group select {
		width: 100%;
		padding: 3vw;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 3vw;
		outline: none;
		box-sizing: border-box;
		transition: border-color 0.3s ease;
	}

	.input-group input:focus,
	.input-group select:focus {
		border-color: #0097FF;
	}

	/* 弹窗底部按钮 */
	.modal-footer {
		display: flex;
		gap: 2vw;
		padding: 3vw;
		border-top: 1px solid #f5f5f5;
	}

	.cancel-btn,
	.confirm-btn {
		flex: 1;
		padding: 3vw;
		border-radius: 4px;
		font-size: 3.2vw;
		font-weight: 500;
		border: none;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.cancel-btn {
		background-color: #f5f5f5;
		color: #666;
	}

	.cancel-btn:hover {
		background-color: #e9e9e9;
	}

	.confirm-btn {
		background-color: #0097FF;
		color: white;
	}

	.confirm-btn:hover {
		background-color: #0080e6;
	}
</style>